package cyf.Login.controller;

import cyf.Login.bean.AdminVO;
import cyf.Login.service.LoginService;
import cyf.Tools.ServerResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登陆相关 Controller层
 */
@Controller
@RequestMapping("/home")
public class LoginController {

    @Autowired
    private LoginService loginService;

    /**
     * 跳转登陆页面
     * @return
     */
    @RequestMapping("/hello")
    public String index() throws IOException {
       return "login";
    }

    /**
     * 管理员退出登录
     */
    @RequestMapping("/leave")
    public String leave( HttpServletRequest req, HttpServletResponse resp){
        HttpSession session = req.getSession();
        session.removeAttribute("Admin");
        return "login";
    }

    /**
     * 管理员登录校验
     * @param username
     * @param password
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody
    public ServerResponse<AdminVO> login(String username, String password, HttpServletRequest req, HttpServletResponse resp){
        HttpSession session = req.getSession();
        if (username == null || username.equals("") || password == null || password.equals("")) {
            ServerResponse serverResponse = ServerResponse.createServerRespsonse(1,"用户名和密码不能为空");
            return serverResponse;
        }
        ServerResponse<AdminVO> serverResponse = loginService.Login(username, password);
        AdminVO vo = serverResponse.getData();
        if(vo!=null){
            session.setAttribute("Admin_account",vo.getAdmin_account());
            session.setAttribute("Admin_name",vo.getAdmin_name());
            session.setAttribute("Admin",vo);
            return ServerResponse.createServerRespsonse(2,"登陆成功",vo);
        }
        return ServerResponse.createServerRespsonse(0,"登陆失败,用户名或密码错误");
    }


}
